package com.server;

import com.server.handler.TcpHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Component
public class NettyTcpServer {

    @Resource
    private ServerBootstrap bootstrap;
    @Resource
    private InetSocketAddress tcpPort;

    private ChannelFuture serverChannelFuture;

    private volatile Channel channel;
    @Resource
    TcpHandler tcpHandler;

    public void start() throws InterruptedException {
        serverChannelFuture = bootstrap.bind(tcpPort);
        channel = serverChannelFuture.channel();
//        channel.closeFuture().;
    }

    /**
     * 在启动servlet的时候，启动netty
     * @throws Exception
     */
    @PostConstruct
    public void init() throws InterruptedException {
        System.out.printf("netty服务器启动");
        this.start();

        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(()->{
            if(!channel.isActive()){
                try {
                    this.start();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },5, 5, TimeUnit.SECONDS);
    }

    /**
     * servlet关闭的时候，关闭netty服务
     * @throws Exception
     */
    @PreDestroy
    public void stop() throws Exception{
        channel.closeFuture();
    }

    public void sendMessage(String msg) throws UnsupportedEncodingException, InterruptedException {
        if(!channel.isActive()){
            this.start();
        }
        ByteBuf byteBuf = Unpooled.wrappedBuffer(msg.getBytes("utf-8"));
//        tcpHandler.channelList.forEach(e->{
//            e.writeAndFlush(byteBuf);
//        });
    }
}
